import React, { useMemo } from 'react';
import { useEditorStore } from '../store/useEditorStore';
import { getYAMLInfo } from '../utils/yaml';
import { formatFileSize, formatTime } from '../utils/file';
import { 
  FileText, 
  Clock, 
  Hash, 
  Type, 
  MapPin, 
  CheckCircle, 
  AlertCircle,
  Info
} from 'lucide-react';

interface StatusBarProps {
  className?: string;
}

const StatusBar: React.FC<StatusBarProps> = ({ className = '' }) => {
  const {
    content,
    filename,
    cursorPosition,
    lastModified,
    validation,
    isDirty
  } = useEditorStore();

  // 计算文件统计信息
  const fileStats = useMemo(() => {
    const lines = content.split('\n');
    const totalLines = lines.length;
    const totalChars = content.length;
    const totalCharsNoSpaces = content.replace(/\s/g, '').length;
    const totalWords = content.trim() ? content.trim().split(/\s+/).length : 0;
    
    // 计算当前光标所在行列
    const beforeCursor = content.substring(0, cursorPosition);
    const currentLine = beforeCursor.split('\n').length;
    const currentColumn = beforeCursor.split('\n').pop()?.length || 0;
    
    return {
      totalLines,
      totalChars,
      totalCharsNoSpaces,
      totalWords,
      currentLine,
      currentColumn: currentColumn + 1 // 1-based indexing
    };
  }, [content, cursorPosition]);

  // 获取YAML信息
  const yamlInfo = useMemo(() => {
    if (!content.trim()) return null;
    try {
      return getYAMLInfo(content);
    } catch {
      return null;
    }
  }, [content]);

  // 状态栏项目
  const statusItems = [
    // 文件名和状态
    {
      icon: FileText,
      label: filename || '未命名文件',
      value: isDirty ? '●' : '',
      tooltip: isDirty ? '文件已修改' : '文件已保存',
      className: isDirty ? 'text-orange-600' : 'text-green-600'
    },
    
    // 光标位置
    {
      icon: MapPin,
      label: '位置',
      value: `${fileStats.currentLine}:${fileStats.currentColumn}`,
      tooltip: `行 ${fileStats.currentLine}, 列 ${fileStats.currentColumn}`
    },
    
    // 文件统计
    {
      icon: Hash,
      label: '统计',
      value: `${fileStats.totalLines}行 ${fileStats.totalWords}词 ${fileStats.totalChars}字符`,
      tooltip: `总行数: ${fileStats.totalLines}\n总词数: ${fileStats.totalWords}\n总字符数: ${fileStats.totalChars}\n不含空格: ${fileStats.totalCharsNoSpaces}`
    },
    
    // YAML信息
    ...(yamlInfo ? [{
      icon: Type,
      label: 'YAML',
      value: `${yamlInfo.keys}键 ${yamlInfo.depth}层`,
      tooltip: `键数量: ${yamlInfo.keys}\n最大深度: ${yamlInfo.depth}\n数据类型: ${yamlInfo.type}`
    }] : []),
    
    // 验证状态
    {
      icon: validation.isValid ? CheckCircle : AlertCircle,
      label: '验证',
      value: validation.isValid ? '正确' : `${validation.errors.length}错误`,
      tooltip: validation.isValid 
        ? 'YAML格式正确' 
        : `发现 ${validation.errors.length} 个错误:\n${validation.errors.map(e => `行${e.line}: ${e.message}`).join('\n')}`,
      className: validation.isValid ? 'text-green-600' : 'text-red-600'
    },
    
    // 最后修改时间
    ...(lastModified ? [{
      icon: Clock,
      label: '修改时间',
      value: formatTime(lastModified),
      tooltip: `最后修改: ${new Date(lastModified).toLocaleString()}`
    }] : [])
  ];

  return (
    <div className={`flex items-center justify-between px-4 py-2 text-xs bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 ${className}`}>
      {/* 左侧状态信息 */}
      <div className="flex items-center space-x-4">
        {statusItems.slice(0, 3).map((item, index) => {
          const Icon = item.icon;
          return (
            <div 
              key={index}
              className={`flex items-center space-x-1 text-gray-600 dark:text-gray-400 ${item.className || ''}`}
              title={item.tooltip}
            >
              <Icon className="w-3 h-3" />
              <span className="font-medium">{item.label}:</span>
              <span>{item.value}</span>
            </div>
          );
        })}
      </div>
      
      {/* 右侧状态信息 */}
      <div className="flex items-center space-x-4">
        {statusItems.slice(3).map((item, index) => {
          const Icon = item.icon;
          return (
            <div 
              key={index + 3}
              className={`flex items-center space-x-1 text-gray-600 dark:text-gray-400 ${item.className || ''}`}
              title={item.tooltip}
            >
              <Icon className="w-3 h-3" />
              <span className="font-medium">{item.label}:</span>
              <span>{item.value}</span>
            </div>
          );
        })}
      </div>
      
      {/* 快捷提示 */}
      <div className="hidden lg:flex items-center space-x-2 text-gray-500 dark:text-gray-500">
        <Info className="w-3 h-3" />
        <span>Ctrl+S保存 | Ctrl+Shift+F格式化 | Ctrl+Shift+V验证</span>
      </div>
    </div>
  );
};

export default StatusBar;